package com.itmayiedu.api.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.itmayiedu.api.service.MemberService;
import com.itmayiedu.base.BaseApiService;
import com.itmayiedu.base.ResponseBase;
import com.itmayiedu.constants.Constants;
import com.itmayiedu.dao.MemberDao;
import com.itmayiedu.entity.UserEntity;
import com.itmayiedu.mq.RegisterMailboxProducer;
import com.itmayiedu.utils.EncrypAES;
import com.itmayiedu.utils.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.LinkedHashMap;

/**
 * @Author cht 【wonderfor@vip.qq.com】
 * @Date 2018/10/19
 */
@RestController
@Slf4j
public class MemberServiceImpl extends BaseApiService implements MemberService {

    @Autowired
    private MemberDao memberDao;

    @Autowired
    private RegisterMailboxProducer registerMailboxProducer;

    @Value("${messages.queue}")
    private String MESSAGEQUEUE;

    @Override
    public ResponseBase findUserById(Long userId) {
        UserEntity userEntity = memberDao.findByID(userId);
        if(userEntity == null) {
            return setResultError("未查找到用户信息");
        }
        return setResultSuccess(userEntity);
    }

    @Override
    public ResponseBase regUser(@RequestBody UserEntity user) {
        //参数验证
        String password = user.getPassword();
        if(StringUtils.isEmpty(password)) {
            return setResultError("密码不能为空");
        }
        String newPassword = EncrypAES.AESEncrypt(password);
        user.setPassword(newPassword);
        Integer result = memberDao.insertUser(user);
        if(result<=0) {
            return setResultError("注册用户信息失败");
        }

        String email = user.getEmail();
        String json = emailJson(email);
        log.info("######会员服务推送消息到消息服务平台######json:{}", json);
        sendMsg(json);

        return setResultSuccess("用户注册成功");
    }

    @Override
    public ResponseBase login(@RequestBody UserEntity user) {
        //1.验证参数
        String username = user.getUsername();
        if(StringUtils.isEmpty(username)) {
            return setResultError("用户名称不能为空!");
        }
        String password = user.getPassword();
        if(StringUtils.isEmpty(password)) {
            return setResultError("密码不能为空!");
        }
        //2.数据库查找账号密码是否正确
        String newPassword = EncrypAES.AESEncrypt(password);
        UserEntity userEntity = memberDao.login(username, newPassword);
        if(userEntity == null) {
            return setResultError("账号或者密码不正确");
        }
        return setLogin(userEntity);
    }

    private ResponseBase setLogin(UserEntity userEntity) {
        //3.如果账号密码正确,生成Token令牌
        String memberToken = TokenUtils.getMemberToken();
        //4.生成Token存放在redis中,key为token,value为userid
        Integer userId = userEntity.getId();
        log.info("######用户信息token存放在redis中,key为:{},value为:{}", memberToken, userId);
        baseRedisService.setString(memberToken, userId+"", Constants.TOKEN_MEMBER_TIME);
        //5.返回token
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("memberToken", memberToken);
        return setResultSuccess(jsonObject);
    }

    @Override
    public ResponseBase findByTokenUser(@RequestParam("token") String token) {
        //1.验证参数
        if(StringUtils.isEmpty("token")) {
            return setResultError("token不能为空!");
        }
        //2.从redis中使用token查找对应userId
        String strUserId = baseRedisService.getString(token);
        if(StringUtils.isEmpty(strUserId)) {
            return setResultError("token无线或已经过期!");
        }
        //3.使用userId查询数据,返回用户信息
        Long userId = Long.parseLong(strUserId);
        UserEntity userEntity = memberDao.findByID(userId);
        if(userEntity == null) {
            return setResultError("未查找到该用户信息");
        }
        userEntity.setPassword(null);
        return setResultSuccess(userEntity);
    }

    @Override
    public ResponseBase findByOpenIdUser(@RequestParam("openid") String openid) {
        //1.验证参数
        if(StringUtils.isEmpty(openid)) {
            return setResultError("系统错误!");
        }
        //2.使用openid查询数据库user表对应数据信息
        UserEntity userEntity = memberDao.findByOpenIdUser(openid);
        if(userEntity == null) {
            return setResultError(Constants.HTTP_RES_CODE_201, "用户未授权QQ登录!");
        }
        Integer userId = userEntity.getId();
        JSONObject jsonObject = setUserRedis(userId);
        return setResultSuccess(jsonObject);
    }

    @Override
    public ResponseBase qqLoginOpenId(@RequestBody UserEntity user) {
        //1.验证参数
        String username = user.getUsername();
        if(StringUtils.isEmpty(username)) {
            return setResultError("用户名称不能为空");
        }
        String password = user.getPassword();
        if(StringUtils.isEmpty(password)) {
            return setResultError("密码不能为空!");
        }
        //2.数据库查找账号密码是否正确
        String newPassWord = EncrypAES.AESEncrypt(password);
        UserEntity userEntity = memberDao.login(username, newPassWord);
        if(userEntity == null) {
            return setResultError("账号或密码不正确");
        }
        //3.关联userid
        String openid = user.getOpenid();
        Integer userId = userEntity.getId();
        memberDao.updateUser(openid, userId);
        JSONObject jsonObject = setUserRedis(userId);
        return setResultSuccess(jsonObject);
    }

    private String emailJson(String email) {
        JSONObject rootJson = new JSONObject();
        JSONObject header = new JSONObject();
        header.put("interfaceType", Constants.MSG_EMAIL);
        JSONObject content = new JSONObject();
        content.put("email", email);
        rootJson.put("header", header);
        rootJson.put("content", content);
        return rootJson.toJSONString();
    }

    private void sendMsg(String json) {
        ActiveMQQueue activeMQQueue = new ActiveMQQueue(MESSAGEQUEUE);
        registerMailboxProducer.sendMsg(activeMQQueue, json);
    }

    public JSONObject setUserRedis(Integer userId) {
        // 3.如果账号密码正确，对应生成token
        String memberToken = TokenUtils.getMemberToken();
        // 4.存放在redis中，key为token value 为 userid
        log.info("####用户信息token存放在redis中... key为:{},value", memberToken, userId);
        baseRedisService.setString(memberToken, userId + "", Constants.TOKEN_MEMBER_TIME);
        // 5.直接返回token
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("memberToken", memberToken);
        return jsonObject;
    }
}
